package com.ymttest.business.service.YMTTrading;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.ymatou.iapi.proditem.service.GetProductInfoByProductIdCall;
import com.ymatou.iapi.productmanager.parameter.product.AddSellerProductRequest;
import com.ymt.base.YmatouEasyCall;
import com.ymt.core.tool.Logger;
import com.ymttest.business.service.ProductManagerCallServiceV2;
import com.ymttest.business.service.ProductPriceCallService;
import com.ymttest.business.service.SellerProductCallService;

/**
 * 洋码头订单商品创建类
 * @author cszhangyi
 *
 */
public class TradingProductVo {

	// 新商品服务为 java 服务
	public static final boolean IS_NEW_PRO_SERVER = true;
	
	public TradingProductVo(String productId, String catalogId) {

		this.productId = productId;
		this.catalogId = catalogId;
	}

	String productId;
	String catalogId;

	int stock;
	int activityStock;

	long activity;
	long productInActivityId;

	public String getProductId() {
		return productId;
	}

	public void setProductId(String productId) {
		this.productId = productId;
	}

	public String getCatalogId() {
		return catalogId;
	}

	public void setCatalogId(String catalogId) {
		this.catalogId = catalogId;
	}

	public int getStock() {
		return stock;
	}

	public void setStock(int stock) {
		this.stock = stock;
	}

	public int getActivityStock() {
		return activityStock;
	}

	public void setActivityStock(int activityStock) {
		this.activityStock = activityStock;
	}

	public long getActivity() {
		return activity;
	}

	public void setActivity(long activity) {
		this.activity = activity;
	}

	public long getProductInActivityId() {
		return productInActivityId;
	}

	public void setProductInActivityId(long productInActivityId) {
		this.productInActivityId = productInActivityId;
	}
	
	/**
	 * 创建普通商品
	 * 
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static TradingProductVo createPro(Long sellerId, String sellerName,
			int stockNum) {

		Map updateMap = new HashMap();

		JSONObject productInfo = null;

		TradingProductVo productVo = null;

		try {

			String proId = null;

			if (IS_NEW_PRO_SERVER) {

				AddSellerProductRequest addProdReq = ProductManagerCallServiceV2
						.initAddSellerProductRequest(Integer.parseInt(sellerId
								.toString()));
				addProdReq.getProduct().getCatalogList().get(0)
						.setStock(stockNum);
				addProdReq.getProduct().getCatalogList().get(1)
						.setStock(stockNum);
				addProdReq.getProduct().getCatalogList().get(0).setPrice(60);
				addProdReq.getProduct().getCatalogList().get(0).setVipPrice(10);
				addProdReq.getProduct().getCatalogList().get(0).setNewPrice(10);
				addProdReq.getProduct().getCatalogList().get(0)
						.setMarketPrice(80);
				proId = ProductManagerCallServiceV2
						.addNewProductOnSale(addProdReq)
						.getAsJsonObject("Data").get("ProductId").getAsString();

				Thread.sleep(3000);

			} else {

				updateMap.put("Product->Catalogs[0]->Num", stockNum);

				// 商品上架
				proId = SellerProductCallService
						.addNewProductNotOnSale(sellerId.intValue(),
								sellerName, updateMap).getJSONObject("Data")
						.getString("ProductID");
			}

			Thread.sleep(5000);

			// 手动同步一次商品
			YmatouEasyCall getProdCall = new YmatouEasyCall("", "GET", null);

			getProdCall
					.setUrl("http://productsync.iapi.ymatou.com/api/cache/mongocrud?ActionType=CreateProduct&ActivityId=0&TransactionId=322487428&ProductId="
							+ proId);
			getProdCall.setData("");
			getProdCall.callService();

			productInfo = getProductInfo(proId, 0);

			productVo = new TradingProductVo(proId, productInfo
					.getJSONArray("CatalogList").getJSONObject(0)
					.getString("CatalogId"));

			productVo.setStock(stockNum);

		} catch (Exception e) {

			e.printStackTrace();
			Logger.info(String.format("###############创建商家 sellerId %s，商品失败",
					sellerId));
		}

		return productVo;
	}

	/**
	 * 创建活动商品
	 * 
	 * @param sellerId
	 * @param sellerName
	 * @param stockNum
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static TradingProductVo createActiverPro(Long sellerId,
			String sellerName, int stockNum) {

		TradingProductVo productVo = null;

		String proId;

		try {

			proId = createPro(sellerId, sellerName, stockNum).getProductId();

			// 创建活动商品
			Map map = ProductPriceCallService.getProductAllowBuyWithActivity(
					sellerId.intValue(), proId, null);

			// 修改 活动商品规格 库存数量
			SellerProductCallService.updateActivityStockNum(
					sellerId.intValue(), proId, stockNum);
			// 查询活动商品 规格id
			JSONObject productInfo = getProductInfo(proId, 0);

			productVo = new TradingProductVo((String) map.get("productId"),
					productInfo.getJSONArray("CatalogList").getJSONObject(0)
							.getString("CatalogId"));

			productVo.setActivity((Integer) map.get("activityId"));
			productVo.setProductInActivityId((Integer) map
					.get("productInActivityId"));

			productVo.setActivityStock(stockNum);

		} catch (Exception e) {
			Logger.info(String.format("###############创建商家 sellerId %s，活动商品失败",
					sellerId));
			Logger.info(e.toString());
		}

		return productVo;
	}

	public static JSONObject getProductInfo(String proId, int retrytimes) {
		try {

			if (retrytimes == 3)
				return null;

			JSONObject productInfo = GetProductInfoByProductIdCall
					.GetProductInfoByProductId(proId).getJSONObject("Data")
					.optJSONObject("Product");

			if (productInfo == null) {
				retrytimes += 1;

				Thread.sleep(5000);
				return getProductInfo(proId, retrytimes);
			}

			else
				return productInfo;

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 
	 * @param proId
	 * @param catalogId
	 * @param isActivityPro
	 *            是否是活动商品
	 * @return
	 */
	public static int getStockNum(String proId, String catalogId,
			boolean isActivityPro) {

		int stockNum = 0;

		try {

			JSONObject productInfo = getProductInfo(proId, 0);
			JSONArray catalogList = productInfo.getJSONArray("CatalogList");

			for (int i = 0; i < catalogList.length(); i++) {

				if (catalogId.equals(catalogList.getJSONObject(i).getString(
						"CatalogId"))) {

					// 如果是活动，返回活动库存
					if (isActivityPro) {
						stockNum = catalogList.getJSONObject(i).getInt(
								"ActivityStock");
					} else {
						stockNum = catalogList.getJSONObject(i).getInt(
								"CatalogStock");
					}

					break;
				}
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return stockNum;
	}
}
